package sv.com.canales.controlador;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import com.example.AdministracionUsuarios.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ConectorSqlLite extends SQLiteOpenHelper{
    private Context contextoAplicacion;

    public ConectorSqlLite(Context context){
        super(context,"BDAdmintracionUsuarios",null,1);
        this.contextoAplicacion = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        System.out.println("====>Iniciando la ejecución del Script de BD");
        try{
            String sql  = obtenerDDL();
            System.out.println(sql);
            sqLiteDatabase.execSQL(obtenerDDL());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
           onCreate(sqLiteDatabase);
    }


    public String obtenerDDL() throws IOException {
        InputStream inputStream = this.contextoAplicacion.getResources().openRawResource(R.raw.ddl_script);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        StringBuilder ddlQuery = new StringBuilder();
        try {
            do{
                line = reader.readLine();
                if(line!=null)
                    ddlQuery.append(line);
            }while (line != null);
        } catch (IOException e) {
            throw e;
        }

        return ddlQuery.toString();
    }

}
